package edu.uestc.wsn;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author joseph
 */
public class SignalGenerator {
    private Communicator c;
    private JFrameBackground frame;
    private static int step = 20;
    private Map<String, LocRss> map;

    public void initServer() {
        c = new Communicator();
        frame = new JFrameBackground(c.getMap());
        c.start();//啓動接受數據線程
        frame.start(); //啓動顯示界面
    }

    public void sendAtClient() {
        map = new HashMap<String, LocRss>();
        //各點初始位置隨機
        for (Integer i = 0; i < 20; i++) {
            String name = i.toString() + "號";
            map.put(name, new LocRss(name, Math.random() * frame.background.getIconWidth(), frame.background.getIconHeight() * Math.random()));
        }

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("enter the sender");
                    List<LocRss> list = new LinkedList(map.values());
                    try {
                        for (LocRss l : list) {
                            Socket socket = new Socket(Constant.host, Constant.port);//建立連接服務器的Socket，需要每個點一個數據。
                            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                            l.setX(l.getX() + step * (Math.random() - 0.5));  //以step/2爲移動半經左、右移動
                            l.setY(l.getY() + step * (Math.random() - 0.5));
                            l.setRss(Math.random());
//                            System.out.println("sending point " + l.getName() + " at (" + l.getX() + "," + l.getY() + ")");
                            out.writeObject(l);
                        }

                        Thread.sleep(Constant.duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.exit(-1);
                    }
                }
            }
        }.start();
    }

    public static void main(String[] args) {
        SignalGenerator s = new SignalGenerator();
        s.initServer(); //服務端模擬使用
        s.sendAtClient(); //客戶端模擬使用
    }
}
